import md5 from 'crypto-js/md5';
import {RSA} from 'react-native-rsa-native';
import {globalService} from 'M/Services';
import ErrorCodes from 'WE/ErrorCodes';

export const buildSign = ({data = {}, appKey}) => {
  globalService.throwError(!appKey, ErrorCodes.InvalidData);
  let value = '';
  Object.keys(data)
    .sort()
    .forEach(k => {
      let datum = data[k];
      if (datum === 0 || datum) {
        value += datum + '|';
      }
    });
  return md5(value + appKey).toString();
};
export function formatOnlyPhone(codePhone) {
  if (!codePhone) {
    return '';
  }
  if (codePhone.indexOf('-') === -1) {
    return codePhone;
  }
  const [code, phone] = codePhone.split('-');
  return `${phone}`;
}

export function validatePhone(phone, region, isThrow = true) {
  if (!phone || !phone.trim()) {
    if (isThrow) {
      throw 'phone.is.null';
    }
    return '';
  }
  phone = formatOnlyPhone(phone.trim());
  if (region && region.pattern && !region.pattern.test(phone)) {
    if (isThrow) {
      throw 'first.phone.character.must.not.be.0';
    }
    return '';
  }
  return phone;
}

export function handlePhone(phone, input, region) {
  if (!input) {
    return phone;
  }
  if (!phone) {
    input.setNativeProps({text: ''});
    return '';
  }
  phone = phone.replace(/[^\d]/g, '');
  if (region && phone.startsWith('0')) {
    phone = phone.substring(1);
    return handlePhone(phone, input, region);
  }
  input.setNativeProps({text: phone});
  return phone;
}

export async function generateRSAKeyPair(keySize = 1024) {
  return await RSA.generateKeys(keySize);
}

export default {
  buildSign,
  validatePhone,
  handlePhone,
  generateRSAKeyPair,
};
export * from 'M/Utils';
